import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    count: 0,
    selected: {},
    viewHeight:""
  },
  mutations: {
    Changeselected(state,_goods){
      // console.log(state,goods)
      const {category,goods,num} = _goods;
      (!state.selected[category])&&(state.selected[category]={})
      if (num>0) {
        state.selected[category][goods.title] = {...goods,num}
      } else {
        delete state.selected[category][goods.title]
      }
      let _count = 0
      for(const key in state.selected) {
        const item = state.selected[key]
        if(Object.keys(item).length){
          for( const _key in item) {
            _count += item[_key].num
          }
        }
      }
      state.count = _count
        Vue.set(state, "count",_count)
      console.log("修改已选",state.count)
      return state.count
    },
    add(state, goods) {
      // this为store实例
      if (state.selected[goods]) {
        state.selected[goods]++
      } else {
        state.selected[goods] = 1
      }
      state.count++
      return count
    },
    reduce(state, goods) {
      if (state.selected[goods]) {
        --state.selected[goods]
        state.selected[goods] <= 0 && delete state.selected[goods]
        state.count > 0 ? --state.count : (state.count = 0)
      }
      return count
    },
    Setviewheight(state,height){
      state.viewHeight = height
      console.log("初始化高度",height)
    }
  },
  getters:{
    _select({selected,count}){
        let obj = {}
        for(const i in selected){
          const items = selected[i]
          for (const x in items ){
            obj[x]=items[x]
          }
        }
        console.log("更新已选",obj)
        return obj
    }
  },
  actions: {}
});